package com.banana.util;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import com.banana.request.Cookie;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CookieUtil {

    public static final JSONArray convertToJson(Collection<Cookie> cookies){
    	JSONArray json = new JSONArray();
    	JSONObject item = null;
    	for (Cookie cookie: cookies) {
    		item = new JSONObject();
    		item.put("name", cookie.getName());
    		item.put("value", cookie.getValue());
    		item.put("domain", cookie.getDomain());
    		if (cookie.getExpiry() != null){
    			item.put("expiry", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(cookie.getExpiry()));
    		}
    		item.put("path", cookie.getPath());
    		item.put("secure", cookie.isSecure());
    		item.put("httpOnly", cookie.isHttpOnly());
    		json.add(item);
		}
    	return json;
    }
    
    public static final Set<Cookie> convertToCollection(JSONArray json){
    	HashSet<Cookie> set = new HashSet<Cookie>();
    	JSONObject item = null;
    	Cookie cookie = null;
    	for (int i = 0;i < json.size() ;i++) {
    		item = json.getJSONObject(i);
    		cookie = new Cookie(item.getString("name"), item.getString("value"));
    		cookie.setDomain(item.getString("domain"));
    		if(item.has("expiry")){
    			try {
					cookie.setExpiry(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(item.getString("expiry")));
				} catch (ParseException e) {
					e.printStackTrace();
				}
    		}
    		cookie.setPath(item.getString("path"));
    		cookie.setSecure(item.getBoolean("secure"));
    		cookie.setHttpOnly(item.getBoolean("httpOnly"));
    		set.add(cookie);
		}
    	return set;
    }
    
    
    public static final void writeToFile(File file,Collection<Cookie> cookies) throws IOException{
    	JSONArray json = convertToJson(cookies);
    	FileUtils.write(file, json.toString());
    }
    
    public static final Set<Cookie> readToCollection(File file) throws IOException{
    	String content = FileUtils.readFileToString(file);
    	JSONArray json = JSONArray.fromObject(content);
    	return convertToCollection(json);
    }
}
